package com.huangkailong.sqlprinter.agent.mysql.driver;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.util.Objects;

/**
 * 5.1.44 之后的的驱动
 *
 * @author huangkailong
 * @since 1.0.0
 */
public class NewDriverAgent extends DriverAgent{
    private static final String CLASS_NAME_ABSTRACT_PREPARED_QUERY = "com.mysql.cj.AbstractPreparedQuery";
    private static final String CLASS_NAME_QUERY_BINDINGS = "com.mysql.cj.QueryBindings";
    private static final String METHOD_NAME_FILL_SEND_PACKET = "fillSendPacket";

    public NewDriverAgent() {
        super();
    }

    @Override
    public boolean doIsSupport(String className) {
        return className.equals(CLASS_NAME_ABSTRACT_PREPARED_QUERY);
    }

    @Override
    public CtClass enhanceClass() throws Exception{
        final ClassPool classPool = ClassPool.getDefault();
        final CtClass abstractPreparedQueryCtClass = classPool.get(CLASS_NAME_ABSTRACT_PREPARED_QUERY);
        final CtClass queryBindingsCtClass = classPool.get(CLASS_NAME_QUERY_BINDINGS);
        final CtMethod fillSendPacketCtMethod = abstractPreparedQueryCtClass.getDeclaredMethod(METHOD_NAME_FILL_SEND_PACKET,
                new CtClass[]{queryBindingsCtClass});
        if(Objects.nonNull(fillSendPacketCtMethod)){
            fillSendPacketCtMethod.insertBefore(getSqlSrc("sql"));
        }
        return abstractPreparedQueryCtClass;
    }

    @Override
    protected String generateSqlGetSrc() {
        return "String sql = asSql();";
    }
}
